package com.example.news360_08;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

/**
 * Created by xx on 2016/5/22.
 */
public class DetailActivity extends Activity {

    private WebView mWb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.detail);
        mWb = (WebView) findViewById(R.id.webview);
        String url = getIntent().getStringExtra("url");
        mWb.loadUrl(url);

        //1、给图片设置js的点击事件(Android调用js代码来实现)
        mWb.getSettings().setJavaScriptEnabled(true);
        mWb.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //给图片添加js点击事件
                addImageClick();
            }
        });
        //2、图片点击事件将图片地址传递给Android代码，然后进行跳转显示，（js代码调用Android代码进行跳转）
        mWb.addJavascriptInterface(new JsCallAndroid() {
            @JavascriptInterface
            @Override
            public void openImage(String url) {
                Toast.makeText(DetailActivity.this, url, Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(DetailActivity.this, ShowImageActivity.class);
                intent.putExtra("url", url);
                startActivity(intent);
            }
        },"imagelistner");
    }

    public interface JsCallAndroid {
        public void openImage(String url);
    }



    //在网页加载完成之后，给图片设置点击事件
    protected void addImageClick() {
        //Android调用js
//		webview.loadUrl("javascript:wave()");
        // 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，
        // 在还是执行的时候调用本地接口传递url过去
        mWb.loadUrl("javascript:(function(){"
                + "var objs = document.getElementsByTagName(\"img\"); "
                + "for(var i=0;i<objs.length;i++)  " + "{"
                + "    objs[i].onclick=function()  " + "   " + " {  "
                + "        window.imagelistner.openImage(this.src);  "
                + "    }  " + "}" + "})()");

    }

}
